package com.zyg.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.common.RedisKey;
import com.zyg.common.ResultCode;
import com.zyg.dao.SysUserMapper;
import com.zyg.model.Result;
import com.zyg.model.UserInfo;
import com.zyg.model.param.SysUserParam;
import com.zyg.model.query.SysUserQueryParam;
import com.zyg.pojo.SysUser;
import com.zyg.service.SysUserService;
import com.zyg.util.JWTUtil;
import com.zyg.util.UserInfoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: 牛二
 * @date: 2020/8/6 15:03
 * @email: 550354312@qq.com
 * @project: zyg_project_demo
 * @describe:
 */
@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
/*    @Autowired
    private AuthorServiceApiClient authorServiceApiClient;*/

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录模块
     * @param loginName 登录账号
     * @param passWord 登录密码
     * @return
     */
    public Result userLogin(String loginName, String passWord){
        Map<String,Object> resultDataMap = new HashMap<>();
        //获取用户信息
        SysUser user = baseMapper.userLogin(loginName,passWord);

        //获取不到用户信息
        if(user == null){
            return new Result().initCodeAndMsg(ResultCode.LOGIN_USER_ERROR);
        }

        //账号被删除
        else if (user.getIsDeleted()){
            return new Result().initCodeAndMsg(ResultCode.LOGIN_USER_ERROR);
        }

        //账号被禁用
        else if(!user.getIsValid()){
            return new Result().initCodeAndMsg(ResultCode.LOGIN_DISABLE_USER_ERROR);
        }

        //生成token中包含的用户信息
        String userInfoJson = JSON.toJSONString(createUserInfo(user));
        //获取token
        Map tokenMap = (Map)JWTUtil.createToken(userInfoJson).getData();
        //将用户信息保存到redis中 过期时间三小时 1000*60*60*3
        redisTemplate.opsForValue().set(RedisKey.PC_USER_TOKEN_INFO + user.getId(),tokenMap.get("token"),3, TimeUnit.HOURS);
        resultDataMap.put("userId",user.getId());
        resultDataMap.put("userName",user.getName());
        resultDataMap.put("loginName",user.getLoginName());
        resultDataMap.put("token",tokenMap.get("token"));
        resultDataMap.put("tokenOverdueTime",tokenMap.get("tokenOverdueTime"));
        return new Result().initSuccess(resultDataMap);
    }

    //生成token中包含的用户信息
    private UserInfo createUserInfo(SysUser user){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setUserLoginName(user.getLoginName());
        userInfo.setUserName(user.getName());
        userInfo.setLesseeId(user.getLesseeId());
        //userInfo.setLesseeName(user.getL());
        userInfo.setCreateTime(DateUtil.formatTime(new Date()));
        return userInfo;
    }

    /**
     * 刷新用户的token
     * @return
     */
    @Override
    public Result refreshUserToken() {
        UserInfo userInfo = UserInfoUtil.getUser();
        String userInfoJson = JSON.toJSONString(userInfo);
        //获取token
        Map tokenMap = (Map)JWTUtil.createToken(userInfoJson).getData();
        return new Result().initSuccess(tokenMap);
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public Result userOutLogin() {
        UserInfo userInfo = UserInfoUtil.getUserSaveInfo();
        if(userInfo != null){
            //退出登录删除redis中缓存的token
            redisTemplate.delete(RedisKey.PC_USER_TOKEN_INFO + userInfo.getUserId());
        }
        return new Result().initSuccess();
    }

    /**
     * 分页获取数据
     * @param queryParam
     * @return
     */
    @Override
    public Result getUserPageList(SysUserQueryParam queryParam) {
        Page page = new Page(queryParam.getPage(),queryParam.getSize());
        baseMapper.selectPage(page,null);
        return new Result().initSuccess(page);
    }

    @Override
    public Result getUserById(String id) {
        SysUser user = baseMapper.selectById(id);
        return new Result().initSuccess(user);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    public Result userAdd(SysUserParam user){
        SysUser newUser = new SysUser();
        BeanUtils.copyProperties(user,newUser);
        baseMapper.insert(newUser);
        return new Result().initSuccess();
    }

    /**
     * 更新用户信息
     * @param userParam
     * @return
     */
    @Override
    public Result updateUser(SysUserParam userParam) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userParam,user);
        baseMapper.updateById(user);
        return new Result().initSuccess();
    }

    @Override
    public Result deleteUserById(String id) {
        baseMapper.deleteById(id);
        return new Result().initSuccess();
    }
}
